<?php

class CSVReader
{

	private $filename;
	private $delimiter;
	private $fields;
	private $filestream;
	
	public function __construct($config)
	{
		$this->filename = $config["input_file"];
		$this->delimiter = $config["delimiter"];
		$this->fields = $config["fields"];
		$this->filestream = fopen($this->filename, "r");
	}
	
	public function read_record()
	{
		if ($this->delimiter != "")
		{
			$csv_record = fgetcsv($this->filestream, $this->delimiter);
		}
		else
		{
			$line = trim(fgets($this->filestream));
			
			if ($line)
			{
				$csv_record = array($line);
			}
			else
			{
				$csv_record = false;
			}
		}
		
		if ($csv_record === false)
		{
			return false;
		}
		
		$record = array();
		foreach ($this->fields as $i => $field)
		{
			$record[$field] = isset($csv_record[$i])?$csv_record[$i]:"";
		}
		
		return (object)$record;
	}

	public function close()
	{
		fclose($this->filestream);
	}
}